package com.abc.cloud.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.abc.cloud.common.exception.MyException;
import com.abc.cloud.dto.im.GroupResp;
import com.abc.cloud.entity.*;
import com.abc.cloud.service.ContactsService;
import com.abc.cloud.service.SysConfigService;
import com.abc.cloud.service.UserService;
import com.abc.cloud.vo.im.AdminUpdateGroupReq;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.abc.cloud.common.utils.PageUtil;
import com.abc.cloud.common.utils.Query;

import com.abc.cloud.dao.GroupDao;
import com.abc.cloud.service.GroupService;


@Service("groupService")
public class GroupServiceImpl extends ServiceImpl<GroupDao, GroupEntity> implements GroupService {

    @Autowired
    private ContactsService contactsService;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private UserService userService;

    @Override
    public PageUtil queryPage(Map<String, Object> params) {
        IPage<GroupEntity> page = this.page(
                new Query<GroupEntity>().getPage(params),
                new QueryWrapper<GroupEntity>()
        );

        return new PageUtil(page);
    }

    @Override
    public List<GroupResp> listByUserId(Long userId) {
        List<GroupResp> res = new ArrayList<>();
        List<GroupEntity> list = this.baseMapper.selectList(new QueryWrapper<GroupEntity>().eq("user_id", userId).eq("status", 1));
        if (list.size() == 0){
            // 自动创建一个分组
            GroupEntity groupFriend = getGroup("我的好友", userId);
            this.baseMapper.insert(groupFriend);

            GroupResp groupResp = BeanUtil.copyProperties(groupFriend, GroupResp.class);
            res.add(groupResp);
        }
        else{
            for (GroupEntity groupEntity : list) {
                GroupResp groupResp = BeanUtil.copyProperties(groupEntity, GroupResp.class);
                groupResp.setUserList(contactsService.queryByGroupId(groupEntity.getId()));
                res.add(groupResp);
            }
        }

        return res;
    }

    @Override
    public void saveGroup(Long userId, String name) {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<GroupEntity>().eq("status", 1)
                .eq("user_id", userId));
        SysConfigEntity sysConfigEntity = sysConfigService.queryKey("用户最大分组数");
        if (count > Integer.parseInt(sysConfigEntity.getSysValue())){
            throw new MyException("最多分组数不超过5个");
        }

        GroupEntity groupEntity = new GroupEntity();
        groupEntity.setName(name);
        groupEntity.setUserId(userId);
        this.baseMapper.insert(groupEntity);
    }

    @Override
    public void updateById(Long userId, Long id, String name, Integer status) {
        GroupEntity groupEntity = this.baseMapper.selectById(id);
        if (!groupEntity.getUserId().equals(userId)){
            throw new MyException("身份验证失败");
        }

        if (name != null){
            groupEntity.setName(name);
        }
        if (status != null){
            // 查询该分组下是否存在联系人
            Integer count = contactsService.count(new LambdaQueryWrapper<ContactsEntity>().eq(ContactsEntity::getGroupId, id));
            if (count > 0){
                throw new MyException("该分组存在联系人，无法删除");
            }
            groupEntity.setStatus(status);
        }
        this.baseMapper.updateById(groupEntity);
    }

    @Override
    public PageUtil adminGroupList(Map<String, Object> params) {
        QueryWrapper<GroupEntity> groupEntityQueryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (key != null && !key.isEmpty()){
            UserEntity userEntity = userService.getOne(new QueryWrapper<UserEntity>().eq("username", key));
            if (userEntity == null){
                return new PageUtil(new ArrayList<>(), 0, 0, 0, 0);
            }
            groupEntityQueryWrapper.eq("user_id", userEntity.getId());
        }

        IPage<GroupEntity> page = this.page(
                new Query<GroupEntity>().getPage(params),
                groupEntityQueryWrapper
        );

        return new PageUtil(page);
    }

    @Override
    public void adminUpdateGroup(AdminUpdateGroupReq adminUpdateGroupReq) {
        GroupEntity groupEntity = this.baseMapper.selectById(adminUpdateGroupReq.getId());
        BeanUtils.copyProperties(adminUpdateGroupReq, groupEntity);
        this.baseMapper.updateById(groupEntity);
    }

    @Override
    public void adminDeleteGroup(List<Long> ids, Integer status) {
        this.baseMapper.deleteGroupByIds(ids, status);
    }

    private GroupEntity getGroup(String name, Long userId){
        GroupEntity groupEntity = new GroupEntity();
        groupEntity.setUserId(userId);
        groupEntity.setName(name);
        return groupEntity;
    }
}